﻿using System;
using System.Text;
using System.Data;
using CRMFramework;
using System.Collections.Generic;
using System.Web;
using Newtonsoft.Json;
using MessageMedia;
using MessageMedia.Common;
using MessageMedia.Diagnostics;
using MessageMedia.Events;
using MessageMedia.Exceptions;
using MessageMedia.Gateway.ActionResult;
using MessageMedia.SMS; 
using CRMBiz;


namespace CRMBiz
{
    public class SmsHelper
    {
        #region Sent Items

        // List used to store sent messages.
        public static List<MessageOut> _sentItems = new List<MessageOut>();

        /// <summary>
        /// Gets or sets the list of sent messages.
        /// </summary>
       public static  List<MessageOut> SentItems
        {
            get { return _sentItems; }
            set { _sentItems = value; }
        }
        #endregion

        #region Pulbic Methods

        public static string SendSMS(string MobileNo, string Message, string userName, string password)
        {
            int Msglength = (Message.Length);
            int LimitNum = 159;
            int flag = 0;
            int RemainString = Msglength - LimitNum;
            string[] MessageString = new string[2];
            if (Msglength > LimitNum)
            {
                MessageString[0] = Message.Substring(0, LimitNum);
                MessageString[1] = Message.Substring(LimitNum, RemainString);
                flag = 1;
            }

            string returnMsg = string.Empty;
            string[] mobileno = MobileNo.Split(',');
            Initialization();
            Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, "Send button clicked.");

            Messaging.MessageController.Settings.Proxy.UseProxy = false;
            Messaging.MessageController.UserAccount.User = userName;
            Messaging.MessageController.UserAccount.Password = password;

            // Create a message queue.
            MessageQueue batch = new MessageQueue();

            for (int i = 0; i < mobileno.Length; i++)
            {
                string cleanedPhoneNumber;
                PhoneNumberValidity validity = Messaging.MessageController.PhoneNumberIsValid(mobileno[i], out cleanedPhoneNumber);
                // Check the validity of the mobile phone number.
                if (validity != PhoneNumberValidity.Mobile && validity != PhoneNumberValidity.Either)
                    continue;
                else
                {
                    if (flag == 1)
                    {
                        for (int j = 0; j < MessageString.Length; j++)
                        {
                            // Add one  Mobile no and message to the Batch.
                            batch.Add(new SMSMessage(cleanedPhoneNumber, MessageString[j]));
                        }
                    }
                    else
                    {
                        batch.Add(new SMSMessage(cleanedPhoneNumber, Message));
                    }
                }
            }           
           
            try
            {
                // Send the batch of messages.
                Messaging.MessageController.SendMessageBatch(batch);
                Messaging.MessageController.SendMessages();

                //Add the sent messages to the list.
                string txtSynchronous = string.Format(
                    "{0} message{1} sent successfully.\n\nMessages in outbox: {2}\nMessages in sent items: {3}",
                    Messaging.MessageController.Settings.BatchSize, (Messaging.MessageController.Settings.BatchSize > 1) ? "s were" : " was",
                    Messaging.MessageController.Settings.BatchSize, SmsHelper.SentItems.Count);

                Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, txtSynchronous);
                returnMsg = "Message successfully sent.";
            }
            catch (Exception ex)
            {
                string txtSynchronous = string.Format("Error occurred when sending messages");
                Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, txtSynchronous);

                throw ex;
            }
            return returnMsg;
        }


        public static string SendSMSFromConsole(string MobileNo, string Message, string userName, string password)
        {
            int Msglength = (Message.Length);
            int LimitNum = 159;
            int flag = 0;
            int RemainString = Msglength - LimitNum;
            string[] MessageString = new string[2];
            if (Msglength > LimitNum)
            {
                MessageString[0] = Message.Substring(0, LimitNum);
                MessageString[1] = Message.Substring(LimitNum, RemainString);
                flag = 1;
            }

            string returnMsg = string.Empty;
            string[] mobileno = MobileNo.Split(',');
            Messaging.MessageController.UserAccount.Country = Countries.Australia;
            //Initialization();
            Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, "Send button clicked.");

            Messaging.MessageController.Settings.Proxy.UseProxy = false;
            Messaging.MessageController.UserAccount.User = userName;
            Messaging.MessageController.UserAccount.Password = password;

            // Create a message queue.
            MessageQueue batch = new MessageQueue();

            for (int i = 0; i < mobileno.Length; i++)
            {
                string cleanedPhoneNumber;
                PhoneNumberValidity validity = Messaging.MessageController.PhoneNumberIsValid(mobileno[i], out cleanedPhoneNumber);
                // Check the validity of the mobile phone number.
                if (validity != PhoneNumberValidity.Mobile && validity != PhoneNumberValidity.Either)
                    continue;
                else
                {
                    if (flag == 1)
                    {
                        for (int j = 0; j < MessageString.Length; j++)
                        {
                            // Add one  Mobile no and message to the Batch.
                            batch.Add(new SMSMessage(cleanedPhoneNumber, MessageString[j]));
                        }
                    }
                    else
                    {
                        batch.Add(new SMSMessage(cleanedPhoneNumber, Message));
                    }
                }
            }

            try
            {
                // Send the batch of messages.
                Messaging.MessageController.SendMessageBatch(batch);
                Messaging.MessageController.SendMessages();

                //Add the sent messages to the list.
                string txtSynchronous = string.Format(
                    "{0} message{1} sent successfully.\n\nMessages in outbox: {2}\nMessages in sent items: {3}",
                    Messaging.MessageController.Settings.BatchSize, (Messaging.MessageController.Settings.BatchSize > 1) ? "s were" : " was",
                    Messaging.MessageController.Settings.BatchSize, SmsHelper.SentItems.Count);

                Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, txtSynchronous);
                returnMsg = "Message successfully sent.";
            }
            catch (Exception ex)
            {
                string txtSynchronous = string.Format("Error occurred when sending messages");
                Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, txtSynchronous);

                throw ex;
            }
            return returnMsg;
        }

        #endregion

        #region "Messaging Event Handler"

        public static void MessageController_SendMessagesComplete(object sender, SendMessagesCompleteEventArgs e)
        {
            if (e.Success)
            {
                Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, "---------SendMessageComplete Method Start-------");
                Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, "Message Successfully Sent.");
                Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, "---------SendMessageComplete Method End-------");
            }
        }
        public static void MessageController_ErrorThrown(object sender, ErrorThrownEventArgs e)
        {
            Messaging.MessageController.Settings.Logger.WriteException(e.Ex);
        }
        public static void MessageController_MessagingStatusChanged(object sender, MessagingStatusEventArgs e)
        {
            Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, "---------Message Status Changed Method Start-------");
            Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, e.Message);
            Messaging.MessageController.Settings.Logger.WriteLine(LogEntryType.Info, "---------Message Status Changed Method End-------");
        }
        #endregion

      
        #region "Private Method"



        private static void Initialization()
        {
            string logFilePath = HttpContext.Current.Server.MapPath("log.txt");
            Messaging.MessageController.Settings.Logger = Logger.CreateLogger(LogType.TextFile, logFilePath);

            // Set the country of origin. By default, this is used to add a country prefix to phone numbers that have no country prefix specified.
            Messaging.MessageController.UserAccount.Country = Countries.Australia;

            // Uncomment the next line to turn ON test mode.
            //Messaging.MessageController.Settings.TestMode = true;

            Logger.Verbosity = LogVerbosity.Maximum;

            Messaging.MessageController.MessagingStatusChanged += MessageController_MessagingStatusChanged;
            Messaging.MessageController.SendMessagesComplete += MessageController_SendMessagesComplete;
            Messaging.MessageController.ErrorThrown += MessageController_ErrorThrown;
        }
        /// <summary>
        /// Updates the delivery status of messages in sent items.
        /// </summary>
        /// <param name="deliveryReports">The delivery reports received from the gateway.</param>
        private void UpdateSentItemsDeliveryStatus(MessageList deliveryReports)
        {
            // Go through the list of delivery reports.
            foreach (DeliveryReport report in deliveryReports)
            {
                // Find the sent message with the same ID as the delivery report and update its status.
                MessageOut message = SmsHelper.SentItems.Find(delegate(MessageOut test) { return test.MessageID == report.MessageID; });
                if (message != null)
                {
                    message.DeliveryStatus = report.Status;
                    message.DeliveryTime = report.Received;
                }
            }
        }

        #endregion
    }
}
